// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/exec/strings.h>

namespace kumo::pollux::aggregate::prestosql {
    StringView Strings::append(StringView value, HashStringAllocator &allocator) {
        POLLUX_DCHECK(!value.isInline());

        maxStringSize = std::max(maxStringSize, value.size());

        // Request sufficient amount of memory to store the whole string
        // (value.size()) and allow some memory left for bookkeeping (header + link
        // to next block).
        const int32_t requiredBytes =
                value.size() + HashStringAllocator::Header::kContinuedPtrSize + 8;

        ByteOutputStream stream(&allocator);
        if (firstBlock == nullptr) {
            // Allocate first block.
            currentBlock = allocator.newWrite(stream, requiredBytes);
            firstBlock = currentBlock.header;
        } else {
            allocator.extendWrite(currentBlock, stream);
        }

        // Check if there is enough space left.
        auto &currentRange = stream.ranges().back();
        if (currentRange.size - currentRange.position < requiredBytes) {
            // Not enough space. Allocate new block.
            ByteRange newRange;
            allocator.newContiguousRange(requiredBytes, &newRange);

            stream.setRange(newRange, 0);
        }

        POLLUX_DCHECK_LE(requiredBytes, stream.ranges().back().size);

        // Copy the string and return a StringView over the copy.
        char *start = stream.writePosition();
        stream.appendStringView(value);
        currentBlock = allocator.finishWrite(stream, maxStringSize * 4).second;
        return StringView(start, value.size());
    }

    void Strings::free(HashStringAllocator &allocator) {
        if (firstBlock != nullptr) {
            allocator.free(firstBlock);
            firstBlock = nullptr;
            currentBlock = {nullptr, nullptr};
        }
    }
} // namespace kumo::pollux::aggregate::prestosql
